import { ChunkEntityUpdateType, SysOrder } from "../../GameDef";
import { ECSFilterEvent, IECSFilter } from "../../lib/kgame/ecs/ECSFilter";
import { ECSSys } from "../../lib/kgame/ecs/ECSSys";
import { ChunkEntityCmp } from "../cmp/ChunkEntityCmp";
import { WorldMgr } from "../scmp/WorldMgr";

/**
 * 区块系统
 */
export class ChunkSys extends ECSSys {

    get updateOrder(): number {
        return SysOrder.chunk;
    }

    get ifilter(): IECSFilter {
        return { includeOne: [ChunkEntityCmp] }
    }

    onAdd(): void {
        const world = this.scene.getCmp(WorldMgr);
        this.filter.on(ECSFilterEvent.cmpAdd, data => {
            const entity = data as ChunkEntityCmp;
            world.chunk.addItem(entity, entity.aabb);
        }, this);
        this.filter.on(ECSFilterEvent.cmpRemove, data => {
            const entity = data as ChunkEntityCmp;
            world.chunk.removeItem(entity);
        }, this);
    }

    onLateUpdate(): void {
        const world = this.scene.getCmp(WorldMgr);
        this.getCmps(ChunkEntityCmp).forEach(entity => {
            if (entity.updateType === ChunkEntityUpdateType.update) {
                world.chunk.updateItem(entity, entity.aabb);
            }
        });
    }

}